package com.manli.api.service;

import com.manli.api.dao.MajorBranchPartnerDao;
import com.manli.api.dto.MajorBranchPartner;
import com.manli.api.pojo.LocationPoint;
import com.manli.api.pojo.QueryParamsBranch;
import com.manli.api.util.*;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.Set;

import com.manli.api.pojo.Result;
import com.manli.api.pojo.SessionInfo;

import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import com.manli.api.dao.BranchDao;
import com.manli.api.dto.Branch;
import org.springframework.transaction.annotation.Transactional;


@Service("branchService")
public class BranchService {
    @Autowired
    BranchDao branchDao;
    @Autowired
    SessionInfoUtils sessionInfoUtils;
    @Autowired
    SQLManager sqlManager;
    @Autowired
    MajorBranchPartnerDao majorBranchPartnerDao;
    
    public Result queryPage(QueryParamsBranch params, HttpServletRequest request) {
    	SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
    	StringBuffer sql = new StringBuffer("SELECT " +
                " a.* " +
                "FROM " +
                " branch a " +
                "  where 1=1 ");

        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getBranchName())?"":" and a.branch_name like '%" + params.getBranchName() + "%'");
        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getStatus())?"":" and a.status = " + params.getStatus()+" " );
        sql.append(sessionInfo.getBranchId() == 1?"":" and a.branch_id = " + sessionInfo.getBranchId() +" " );
        sql.append(" order by a.status desc , a.branch_id desc  ");

        SQLReady sqlReady = new SQLReady(sql.toString());

        PageQuery<Branch> pageQuery = new PageQuery<Branch>(params.getPage(),params.getLimit());
        PageQuery<Branch> query =sqlManager.execute(sqlReady,Branch.class,pageQuery);

        //查询总店下的多个主营类别
        query.getList().forEach(branch -> {
            String sql1 = "select a.major_type_id from major_branch_partner a left join major_type b on a.major_type_id = b.major_type_id where partner_id is null and branch_id = " + branch.getBranchId();
            SQLReady sqlReady1 = new SQLReady(sql1);
            List<Integer> list = sqlManager.execute(sqlReady1,Integer.class);
            branch.setMajorTypeId(list);

            String sql2 = "select GROUP_CONCAT(b.major_name) major_name from major_branch_partner a left join major_type b on a.major_type_id = b.major_type_id where a.partner_id is null and a.branch_id = " + branch.getBranchId();
            SQLReady sqlReady2 = new SQLReady(sql2);
            List<String> list1 = sqlManager.execute(sqlReady2,String.class);
            branch.setMajorName(list1.size()>0?list1.get(0):"");
        });

        return ResultUtil.success(query.getList(),query.getTotalRow());
    }

    
    public Result queryAll(QueryParamsBranch params,HttpServletRequest request) {
    	SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        StringBuffer sql = new StringBuffer("SELECT " +
                " a.* " +
                "FROM " +
                " branch a " +
                "  where 1=1 ");

        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getBranchName())?"":" and a.branch_name like '%" + params.getBranchName() + "%'");
        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getStatus())?"":" and a.status = " + params.getStatus()+" " );
        sql.append(sessionInfo.getBranchId() == 1?"":" and a.branch_id = " + sessionInfo.getBranchId() +" " );
        sql.append(" order by a.status desc , a.branch_id desc  ");

        SQLReady sqlReady = new SQLReady(sql.toString());
        List<Branch> query =sqlManager.execute(sqlReady,Branch.class);

        //查询总店下的多个主营类别
        query.forEach(branch -> {
            String sql1 = "select a.major_type_id from major_branch_partner a left join major_type b on a.major_type_id = b.major_type_id where branch_id = " + branch.getBranchId();
            SQLReady sqlReady1 = new SQLReady(sql1);
            List<Integer> list = sqlManager.execute(sqlReady1,Integer.class);
            branch.setMajorTypeId(list);

            String sql2 = "select GROUP_CONCAT(b.major_name) major_name from major_branch_partner a left join major_type b on a.major_type_id = b.major_type_id where branch_id = " + branch.getBranchId();
            SQLReady sqlReady2 = new SQLReady(sql2);
            List<String> list1 = sqlManager.execute(sqlReady2,String.class);
            branch.setMajorName(list1.size()>0?list1.get(0):"");
        });


        return ResultUtil.success(query);
    }

    
    public Result getById(Integer branchId) {
        Branch branch = branchDao.single(branchId);
        return ResultUtil.success(branch);
    }

    @Transactional
    public Result save(Branch branch) {
        //判断值为空
        ObjectEmptyUtil.branchIsEmpty(branch);

        //判断branch名称是否重复
        List<Branch> list = branchDao.execute("select * from branch where branch_name = ?",branch.getBranchName());
        if(list.size() > 0){
            return ResultUtil.error(-1,"主店名称重复");
        }
        LocationPoint point = new LocationPoint(Double.valueOf(branch.getLongitude()),Double.valueOf(branch.getLatitude()));
        branch.setLongitudeWgs(LocationUtils.gcj02_To_Wgs84(point).getLongitude().toString());
        branch.setLatitudeWgs(LocationUtils.gcj02_To_Wgs84(point).getLatitude().toString());
        Object id = branchDao.insertReturnKey(branch).getKey();
        //主营类别表操作
        if(branch.getMajorTypeId().size() == 0){
            return ResultUtil.error(-1,"请选择主营类别");
        }

        branch.getMajorTypeId().forEach(majorid -> {
            MajorBranchPartner majorBranchPartner = new MajorBranchPartner();
            majorBranchPartner.setBranchId(Integer.parseInt(id.toString()));
            majorBranchPartner.setMajorTypeId(majorid);
            majorBranchPartnerDao.insert(majorBranchPartner);
        });

        return ResultUtil.success();
    }

    @Transactional
    public Result updateById(Branch branch) {
        //判断值为空
        ObjectEmptyUtil.branchIsEmpty(branch);

        //判断branch名称是否重复
        List<Branch> list = branchDao.execute("select * from branch where branch_name = ? and branch_id != ?",branch.getBranchName(),branch.getBranchId());
        if(list.size() > 0){
            return ResultUtil.error(-1,"主店名称重复");
        }
        LocationPoint point = new LocationPoint(Double.valueOf(branch.getLongitude()),Double.valueOf(branch.getLatitude()));
        branch.setLongitudeWgs(LocationUtils.gcj02_To_Wgs84(point).getLongitude().toString());
        branch.setLatitudeWgs(LocationUtils.gcj02_To_Wgs84(point).getLatitude().toString());
        branchDao.updateTemplateById(branch);

        //主营类别表操作
        if(branch.getMajorTypeId().size() == 0){
            return ResultUtil.error(-1,"请选择主营类别");
        }

        majorBranchPartnerDao.executeUpdate("delete from major_branch_partner where branch_id = ? and partner_id is null",branch.getBranchId());


        Set<Integer> majorTypeids = new HashSet<>();
        majorTypeids.addAll(branch.getMajorTypeId());
        majorTypeids.forEach(majorid -> {
            MajorBranchPartner majorBranchPartner = new MajorBranchPartner();
            majorBranchPartner.setBranchId(branch.getBranchId());
            majorBranchPartner.setMajorTypeId(majorid);
            majorBranchPartnerDao.insert(majorBranchPartner);
        });
        return ResultUtil.success();
    }
    @Transactional
	public Result updateTemplateById(Branch branch) {
        branchDao.updateTemplateById(branch);
        return ResultUtil.success();
    }
    @Transactional
    public Result removeById(Integer branchId) {
        branchDao.deleteById(branchId);
        return ResultUtil.success();
    }

    @Transactional
    public Result removeByIds(List<Integer> ids) {
        for (Integer id:ids) {
            branchDao.deleteById(id);
        }
        return ResultUtil.success();
    }



}
